import os
import requests
from common import factory_connection
from common import close_connection
from common import create_token,get_ticket_id, get_fcodebyticket

token = create_token()
home_dir = os.path.expanduser("~")
file_path = os.path.join(home_dir, 'Downloads', 'ticket.tsv')
#sql_code = 'meow';
sql_code = 'colorful';
#sql_code = 'wf';


def factory_request(factory_code, order_no):
    url = "/api/tkt/option"
    URL = f"https://{factory_code}.haishenxiyi.net{url}"
    headers = {
        'Authorization': token,
        'Content-Type': 'application/json'
    }
    body_data = {
        'ticketId': int(order_no),
        'ticketBackState': 'HAVEKNOWN',
        'remark': '数据处理'
    }
    response = requests.post(URL,headers=headers,json=body_data)
    print(URL)
    print("Status Code:", response.status_code)
    print("Response Text:", response.text)


def update_ticket(factory_code, ticket_id):
    connection = factory_connection(factory_code)
    cursor = connection.cursor()
    cursor.execute(f'update tkt_ticket SET `status` = "FINISHED" where channel_ticket_id = {ticket_id} and channel_id = (select id from sys_channel where code = "dajingxi")')
    connection.commit()
    close_connection(connection)


with open(file_path, 'r') as file:
    lines = file.readlines()

for line in lines:
    splited = line.split("\t")

    if len(splited) <= 1:
        order_no = splited[0].strip()
        fcode = None
    else:
        fcode = splited[0].strip()
        order_no = splited[1].strip()

    if not fcode:
        fcode = get_fcodebyticket(order_no, sql_code)

    if not fcode:
        print('fcode为空')
        continue
    #update_ticket(fcode,order_no)
    if sql_code == "wf":
        channel_code = "dajingxi"
    else:
        channel_code = sql_code
    ticket_id = get_ticket_id(fcode, order_no, channel_code)
    if ticket_id:
        factory_request(fcode, ticket_id)